<!-- 购物车 -->
<template>
  <div class="cart-container">
    <HeadNav title="购物车"></HeadNav>
    
    <!-- 购物车为空时显示 -->
    <div v-if="cartItems.length === 0" class="empty-cart">
      <el-empty description="购物车空空如也">
        <el-button type="primary" @click="$router.push('/')">去逛逛</el-button>
      </el-empty>
    </div>

    <!-- 购物车有商品时显示 -->
    <div v-else class="cart-content">
      <!-- 商品列表 - 表格形式 -->
      <div class="cart-table">
        <el-table
          ref="cartTable"
          :data="cartItems"
          style="width: 100%"
          :row-key="row => row.id + '-' + row.colorId + '-' + row.capacityId"
          empty-text="购物车是空的"
          @selection-change="handleSelectionChange"
        >
          <el-table-column 
            type="selection" 
            width="55" 
            align="center"
            :selectable="() => true"
          ></el-table-column>
          
          <el-table-column label="商品信息" min-width="300">
            <template #default="{row}">
              <div class="product-cell">
                <img class="product-image" :src="getImageUrl(row.image)" :alt="row.name">
                <div class="product-info">
                  <div class="product-name">{{ row.name }}</div>
                  <div class="product-spec">{{ row.colorName }} / {{ row.capacityValue }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="单价" width="120">
            <template #default="{row}">
              <div class="product-price">¥{{ row.price.toFixed(2) }}</div>
            </template>
          </el-table-column>
          
          <el-table-column label="数量" width="150" align="center">
            <template #default="{row, $index}">
              <el-input-number 
                v-model="row.quantity" 
                :min="1" 
                :max="99" 
                size="small"
                @change="handleQuantityChange($index)"
                controls-position="right"
              ></el-input-number>
            </template>
          </el-table-column>
          
          <el-table-column label="小计" width="120">
            <template #default="{row}">
              <div class="product-total">¥{{ (row.price * row.quantity).toFixed(2) }}</div>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="80" align="center">
            <template #default="{$index}">
              <el-button 
                type="danger" 
                icon="el-icon-delete" 
                circle 
                size="mini"
                @click="confirmRemoveItem($index)"
                class="delete-btn"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 结算栏 -->
      <div class="cart-footer">
        <div class="footer-left">
          <el-checkbox v-model="allSelected" @change="toggleSelectAll">全选</el-checkbox>
          <el-button type="text" @click="confirmClearCart">清空购物车</el-button>
        </div>
        <div class="footer-right">
          <div class="total-info">
            <span>已选 {{ selectedCount }} 件</span>
            <span class="total-price">合计: <strong>¥{{ totalPrice.toFixed(2) }}</strong></span>
          </div>
          <el-button 
            type="danger" 
            :disabled="selectedCount === 0"
            @click="checkout"
          >
            去结算({{ selectedCount }})
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import HeadNav from '../components/HeadNav.vue'
import { mapState, mapMutations } from 'vuex'

export default {
  name: 'ShoppingCart',
  components: {
    HeadNav
  },
  data() {
    return {
      allSelected: false,
      selectedRows: []
    }
  },
  computed: {
    ...mapState(['cartItems']),
    
    // 计算选中的商品数量
    selectedCount() {
      return this.selectedRows.reduce((total, item) => total + item.quantity, 0)
    },
    
    // 计算总价
    totalPrice() {
      return this.selectedRows.reduce((total, item) => {
        return total + (item.price * item.quantity)
      }, 0)
    }
  },
  methods: {
    ...mapMutations([
      'updateCartItemQuantity',
      'removeCartItem',
      'clearCartItems'
      
    ]),
    
    getImageUrl(relativePath) {
      try {
        return require(`@/assets/img/goods/${relativePath}`)
      } catch (e) {
        return require('@/assets/img/goods/dian-1.png')
      }
    },
    
    // 数量变化处理
    handleQuantityChange(index) {
      this.updateCartItemQuantity({
        index,
        quantity: this.cartItems[index].quantity
      })
    },
    
    // 处理表格选择变化
 handleSelectionChange(selection) {
   this.selectedRows = selection
   this.allSelected = selection.length === this.cartItems.length
 },
    
    // 确认删除商品
    confirmRemoveItem(index) {
      this.$confirm('确定要删除该商品吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            this.removeCartItem(index)
            setTimeout(() => {
              done()
              setTimeout(() => {
                instance.confirmButtonLoading = false
                this.$message.success('删除成功!')
              }, 200)
            }, 500)
          } else {
            done()
          }
        }
      }).catch(() => {})
    },
    
    // 确认清空购物车
    confirmClearCart() {
      this.$confirm('确定要清空购物车吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            this.clearCartItems()
            setTimeout(() => {
              done()
              setTimeout(() => {
                instance.confirmButtonLoading = false
                this.$message.success('购物车已清空!')
              }, 200)
            }, 500)
          } else {
            done()
          }
        }
      }).catch(() => {})
    },
    
    // 全选/取消全选
    toggleSelectAll(selected) {
      this.$refs.cartTable.clearSelection()
      if (selected) {
        this.$refs.cartTable.toggleAllSelection()
      }
    },
    
 // 结算方法优化
 checkout() {
   if (this.selectedCount === 0) {
     this.$message.warning('请选择要结算的商品')
     return
   }
   
   // 准备要传递的商品数据
   const orderItems = this.selectedRows.map(item => ({
     id: item.id,
     image: item.image,
     name: item.name,
     colorName: item.colorName,
     capacityValue: item.capacityValue,
     price: item.price,
     quantity: item.quantity,
     subtotal: (item.price * item.quantity).toFixed(2)
   }))
   
   // 使用路由参数传递数据
   this.$router.push({
     path: '/orders',
     query: {
       items: encodeURIComponent(JSON.stringify(orderItems)),
       total: this.totalPrice.toFixed(2),
       count: this.selectedCount
     }
   })
 }
  },
  watch: {
    cartItems: {
      handler(newVal) {
        // 如果购物车被清空，重置全选状态
        if (newVal.length === 0) {
          this.allSelected = false
          this.selectedRows = []
        }
      },
      deep: true
    }
  },
  mounted() {
    // 初始化时设置已选中的商品
    this.$nextTick(() => {
      this.cartItems.forEach(item => {
        if (item.selected) {
          this.$refs.cartTable.toggleRowSelection(item, true)
        }
      })
    })
  }
}
</script>
<style scoped>
.cart-container {
  max-width: 1200px;
  margin: 0 auto;
  padding-bottom: 60px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.empty-cart {
  padding-top: 100px;
  text-align: center;
}

.cart-content {
  padding: 15px;
}

.cart-list {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.cart-item:last-child {
  border-bottom: none;
}

.item-select {
  width: 40px;
  text-align: center;
}

.item-image {
  width: 80px;
  height: 80px;
  margin: 0 15px;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.item-info {
  flex: 1;
  min-width: 0;
}

.item-name {
  font-size: 16px;
  color: #333;
  margin-bottom: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.item-spec {
  font-size: 12px;
  color: #999;
  margin-bottom: 10px;
}

.item-price {
  font-size: 16px;
  color: #ff6700;
  font-weight: bold;
}

.item-quantity {
  width: 120px;
  margin: 0 15px;
}

.item-total {
  width: 100px;
  font-size: 16px;
  color: #ff6700;
  font-weight: bold;
  text-align: right;
}

.item-action {
  width: 40px;
  text-align: center;
}

.cart-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 50px;
  padding: 0 15px;
  background: #fff;
  box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
  z-index: 10;
}

.footer-left {
  display: flex;
  align-items: center;
}

.footer-left .el-button {
  margin-left: 15px;
}

.footer-right {
  display: flex;
  align-items: center;
}

.total-info {
  margin-right: 15px;
  text-align: right;
}

.total-info span {
  display: block;
  font-size: 12px;
  color: #666;
}

.total-price {
  font-size: 16px;
  color: #ff6700;
}

.total-price strong {
  font-size: 18px;
}

@media (max-width: 768px) {
  .item-image {
    width: 60px;
    height: 60px;
    margin: 0 10px;
  }
  
  .item-quantity {
    width: 100px;
    margin: 0 10px;
  }
  
  .item-total {
    width: 80px;
  }
}
.product-cell {
  display: flex;
  align-items: center;
  padding: 8px 0;
}

.product-image {
  width: 150px;
  height: 150px;
  object-fit: contain;
  margin-right: 12px;
}

.product-info {
  flex: 1;
  margin-left: 50px;
}

.product-name {
  font-weight: 800;
  font-size: 15px;
  margin-bottom: 4px;
}

.product-spec {
  color: #888;
  font-size: 14px;
}

.product-price,
.product-total {
  font-weight: 500;
  font-size: 15px;
  
}

.delete-btn {
  padding: 6px;
}
</style>